"""
全局异常处理器
统一管理FastAPI应用的异常处理逻辑
"""

from fastapi import FastAPI, Request, HTTPException
from fastapi.responses import JSONResponse

from config.logging_config import get_logger

logger = get_logger(__name__)


class ExceptionHandlers:
    """异常处理器管理类"""

    @staticmethod
    async def global_exception_handler(request: Request, exc: Exception) -> JSONResponse:
        """全局异常处理器"""
        # 获取请求ID
        request_id = getattr(request.state, 'request_id', 'unknown')

        # 记录详细的异常信息
        logger.error(
            f"[{request_id}] 全局异常捕获 - 请求: {request.method} {request.url} - "
            f"异常类型: {type(exc).__name__} - 异常信息: {str(exc)}",
            exc_info=True
        )

        # 返回统一的错误响应
        response = JSONResponse(
            status_code=500,
            content={
                "error": "内部服务器错误",
                "message": str(exc),
                "type": type(exc).__name__,
                "path": str(request.url),
                "method": request.method,
                "request_id": request_id
            }
        )
        response.headers["X-Request-ID"] = request_id
        return response

    @staticmethod
    async def http_exception_handler(request: Request, exc: HTTPException) -> JSONResponse:
        """HTTP异常处理器"""
        request_id = getattr(request.state, 'request_id', 'unknown')

        logger.warning(
            f"[{request_id}] HTTP异常 - 请求: {request.method} {request.url} - "
            f"状态码: {exc.status_code} - 详情: {exc.detail}"
        )

        response = JSONResponse(
            status_code=exc.status_code,
            content={
                "error": "请求处理失败",
                "message": exc.detail,
                "status_code": exc.status_code,
                "path": str(request.url),
                "method": request.method,
                "request_id": request_id
            }
        )
        response.headers["X-Request-ID"] = request_id
        return response

    @staticmethod
    async def value_error_handler(request: Request, exc: ValueError) -> JSONResponse:
        """参数错误处理器"""
        request_id = getattr(request.state, 'request_id', 'unknown')

        logger.warning(
            f"[{request_id}] 参数错误 - 请求: {request.method} {request.url} - 错误: {str(exc)}"
        )

        response = JSONResponse(
            status_code=400,
            content={
                "error": "参数错误",
                "message": str(exc),
                "path": str(request.url),
                "method": request.method,
                "request_id": request_id
            }
        )
        response.headers["X-Request-ID"] = request_id
        return response

    @staticmethod
    async def validation_error_handler(request: Request, exc: Exception) -> JSONResponse:
        """验证错误处理器（用于Pydantic验证错误等）"""
        request_id = getattr(request.state, 'request_id', 'unknown')

        logger.warning(
            f"[{request_id}] 验证错误 - 请求: {request.method} {request.url} - 错误: {str(exc)}"
        )

        response = JSONResponse(
            status_code=422,
            content={
                "error": "请求数据验证失败",
                "message": str(exc),
                "path": str(request.url),
                "method": request.method,
                "request_id": request_id
            }
        )
        response.headers["X-Request-ID"] = request_id
        return response


def register_exception_handlers(app: FastAPI) -> None:
    """
    注册所有异常处理器到FastAPI应用

    Args:
        app: FastAPI应用实例
    """
    handlers = ExceptionHandlers()

    # 注册全局异常处理器
    app.add_exception_handler(Exception, handlers.global_exception_handler)

    # 注册HTTP异常处理器
    app.add_exception_handler(HTTPException, handlers.http_exception_handler)

    # 注册参数错误处理器
    app.add_exception_handler(ValueError, handlers.value_error_handler)

    # 可以根据需要添加更多特定异常处理器
    # app.add_exception_handler(ValidationError, handlers.validation_error_handler)

    logger.info("✅ 异常处理器注册完成")


def setup_custom_exception_handlers(app: FastAPI) -> None:
    """
    设置自定义异常处理器的便捷方法
    包含更多高级功能，如错误统计、告警等
    """

    # 错误统计计数器（可选功能）
    error_stats = {
        "total_errors": 0,
        "http_errors": 0,
        "validation_errors": 0,
        "server_errors": 0
    }

    @app.exception_handler(Exception)
    async def enhanced_global_exception_handler(request: Request, exc: Exception):
        error_stats["total_errors"] += 1
        error_stats["server_errors"] += 1

        # 可以在这里添加更多增强功能：
        # - 错误告警
        # - 详细日志记录
        # - 错误统计上报

        return await ExceptionHandlers.global_exception_handler(request, exc)

    @app.exception_handler(HTTPException)
    async def enhanced_http_exception_handler(request: Request, exc: HTTPException):
        error_stats["total_errors"] += 1
        error_stats["http_errors"] += 1

        return await ExceptionHandlers.http_exception_handler(request, exc)

    @app.exception_handler(ValueError)
    async def enhanced_value_error_handler(request: Request, exc: ValueError):
        error_stats["total_errors"] += 1
        error_stats["validation_errors"] += 1

        return await ExceptionHandlers.value_error_handler(request, exc)

    # 添加获取错误统计的端点（可选）
    @app.get("/debug/error-stats")
    async def get_error_stats():
        """获取错误统计信息（仅在调试模式下可用）"""
        return error_stats

    logger.info("✅ 增强版异常处理器设置完成")
